package cn.wizzer.app.web.commons.ext.websocket.action.msg.user;

import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.UserChatMsg;
import cn.wizzer.app.user.modules.models.enums.MsgStatusEnum;
import cn.wizzer.app.user.modules.models.vo.ChatUserVO;
import cn.wizzer.app.user.modules.services.UserChatMsgService;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.web.commons.ext.websocket.filter.TokenFilter;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.action.NettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.base.NettyCache;
import cn.wizzer.app.web.commons.ext.websocket.main.result.ChatResult;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.page.Pagination;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zl
 * @date 2020/6/3 16:49
 */
@IocBean
@NettyAction(uri = "/user/history", filters = {TokenFilter.class})
public class UserHistoryAction extends BaseNettyAction {

    @Inject
    @Reference
    private UserChatMsgService chatMsgService;
    @Inject
    @Reference
    private UserService userService;

    /**
     * 用户查询发给自己的历史记录
     *
     * @param income
     * @param params
     * @return
     */
    @Override
    public Result action(Channel income, JSONObject params) {
        String userId = params.getString("appid");
        Pagination pagination = chatMsgService.listPage(params.getInteger("pageNumber"),
                params.getInteger("pageSize"), userId);
        List<UserChatMsg> unReadList = new ArrayList<>();
        List<UserChatMsg> userChatMsgList = pagination.getList(UserChatMsg.class);
        for (UserChatMsg userChatMsg : userChatMsgList) {
            //当消息为未读状态且接收人是自己时，添加入未读消息集合
            if(userChatMsg.getStatus() == MsgStatusEnum.UN_READ && userId.equals(userChatMsg.getToUser())){
                unReadList.add(userChatMsg);
            }
        }
        if(unReadList.size() > 0){
            List<String> ids = unReadList.stream().map(UserChatMsg::getId).collect(Collectors.toList());
            //修改未读记录为已读
            chatMsgService.update(Chain.make("status", MsgStatusEnum.READ), Cnd.where("id", "in", ids));
            //通知对应客服已读记录
            User user = userService.fetch(userId);
            ChatUserVO targetAttendant = NettyCache.globalGet(NettyCache.localGet(income,"targetAttendant"));
            for (UserChatMsg userChatMsg : unReadList) {
                if(targetAttendant != null){
                    NettyMsgUtil.send(targetAttendant.getChannel(), ChatResult.MessageTypeEnum.ACTION, ChatResult.ActionEnum.READ, user,userChatMsg.getId());
                }
            }
        }
        return Result.success().addData(pagination);
    }
}
